package com.liull.netty.cust_protocol;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 17:06 2020/11/15
 * @Modified By:
 */
public class PersonServerHandler extends SimpleChannelInboundHandler<PersonProtocol> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception {
        System.out.println("收到来自客户端的消息：" + msg);
        // 返回一个消息
        String resp = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        ctx.writeAndFlush(new PersonProtocol(resp.getBytes(CharsetUtil.UTF_8).length, resp.getBytes(CharsetUtil.UTF_8)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().closeFuture().sync();
    }
}
